package com.maxsalad.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * Created by 2014-400 on 2016-01-25.
 */
public class JsonUtil {
    private static transient Logger log = LoggerFactory.getLogger(JsonUtil.class);
    private static SerializerFeature[] features = {SerializerFeature.WriteNullNumberAsZero,
            SerializerFeature.WriteNullStringAsEmpty,
            SerializerFeature.DisableCircularReferenceDetect};

    /**
     * 反序列化
     *
     * @param s
     * @return
     */
    public static Object deserialize(String s) {

        return deserialize(s, Object.class);
    }

    /**
     * 反序列化
     *
     * @param s
     * @param cls
     * @return
     */
    public static Object deserialize(String s, Class<?> cls) {
        Object vo = null;
        if (s != null && s.trim().length() > 0) {
            try {
                vo = JSON.parseObject(s, cls);
            } catch (Exception e) {
                log.error("deserialize error:" + s, e);
            }
        }
        return vo;
    }

    public static Object deserialize(String s, Class<?> cls, Feature feature) {
        Object vo = null;
        if (s != null && s.trim().length() > 0) {
            try {
                vo = JSON.parseObject(s, cls, feature);
            } catch (Exception e) {
                log.error("deserialize error:" + s, e);
            }
        }
        return vo;
    }

    /**
     * 序列化
     *
     * @param obj
     * @return
     */
    public static String serialize(Object obj) {
        String jsonString = null;
        if (obj != null) {
            try {
                jsonString = JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
            } catch (Exception e) {
                log.error("serialize error:", e);
            }
        }
        return jsonString;
    }

    /**
     * 实体转map
     *
     * @param obj
     * @return
     */
    public static Map toMap(Object obj) {
        if (obj instanceof Map) {
            return (Map) obj;
        } else {
            return (Map) deserialize(serialize(obj));
        }
    }

    /**
     * 将list内的元素转成MAP
     *
     * @param list
     * @return
     */
    public static List<Map> listItemToMap(List list) {
        return (List<Map>) deserialize(serialize(list));
    }

}
